package com.cspm.common.proxy;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

/**
 * 定义选择数据源切面
 */
public class DynamicDataSourceAspect {

    private static final Logger logger = Logger
            .getLogger(DynamicDataSourceAspect.class);

    public void pointCut() {
    }

    @Pointcut("execution(* com.cspm.gen.dao.*(..))")
    public void before() {
    }

    @Before(value = "before()")
    public void before(JoinPoint point) {
        Object target = point.getTarget();
        if (target.toString().contains("CustomShiroSessionDAO")) {
            //不检查的DAO类
            return;
        }
        String methodName = point.getSignature().getName();
        Class<?>[] clazz = target.getClass().getInterfaces();
        Class<?>[] parameterTypes = ((MethodSignature) point.getSignature())
                .getMethod().getParameterTypes();
        try {
            Method method = clazz[0].getMethod(methodName, parameterTypes);
            if (method != null && method.isAnnotationPresent(DataSource.class)) {
                DataSource data = method.getAnnotation(DataSource.class);
                DynamicDataSourceHolder.putDataSource(data.value());
            }
        } catch (Exception e) {
            logger.error(String.format(
                    "Choose DataSource error, method:%s, msg:%s", methodName,
                    e.getMessage()));
        }
    }

    @Pointcut("execution(* com.cspm.gen.dao.*(..))")
    public void after() {
    }

    @After(value = "after()")
    public void after(JoinPoint point) {
        DynamicDataSourceHolder.clearDataSource();
    }
}